-- Books are fact bases, where facts are represented by sentences

Book = class("Book")

---

function Book:initialize()

	self.sentencesByVerbs = {}
	self.matchingVariables = {}
end

---

function Book:addSentence(sentence)

	local verb
	local splitedSentences = sentence:split()
	
	for i, splitedSentence in ipairs(splitedSentences)
	do
		verb = splitedSentence:getVerb()
		
		if not self.sentencesByVerbs[verb]
		then
			self.sentencesByVerbs[verb] = {}
		end
		
		self.sentencesByVerbs[verb][#(self.sentencesByVerbs[verb]) + 1] = splitedSentence
	end
end

---

function Book:matchSentence(sentencesToMatch, matchingVariables)

	if matchingVariables
	then
		self.matchingVariables = matchingVariables
	else
		self.matchingVariables = {}
	end
	
	for sentenceToMatchIndex, sentenceToMatch in ipairs(sentencesToMatch:split(true))
	do
		local found = false
		local sentencesByVerb = self.sentencesByVerbs[sentenceToMatch:getVerb()]
		
		if sentencesByVerb
		then
			for i, bookSentence in ipairs(sentencesByVerb)
			do
				if sentenceToMatch:equal(bookSentence, self.matchingVariables, {ignoreConjuctions = true})
				then
					found = true
					break
				end
			end
		end
		
		if not found
		then
			return false
		end
	end
	
	return true
end

---

function Book:__tostring()

	local string = "" 
	
	for verb, sentencesByVerb in pairs(self.sentencesByVerbs)
	do
		string = string .. "--- Verb: " .. verb .. "\n"
		
		for i, sentence in ipairs(sentencesByVerb)
		do
			string = string .. tostring(sentence) .. "\n" 
		end
	end 
	
	return string
end